use tauri::{Manager, WindowEvent,Emitter};  // 添加 Emitter trait
use serde::{Deserialize, Serialize};
use std::fs;

// 获取版本信息
#[tauri::command]
fn get_app_version(app: tauri::AppHandle) -> String {
    let config = app.config();
    config.version.clone().unwrap_or_else(|| "unknown".into())
}

// 导出json文件
#[derive(Debug, Serialize, Deserialize)]
struct ExportData {
    data: serde_json::Value,
    file_path: String, // 前端传递的完整路径
}

#[tauri::command]
async fn export_to_json(data: ExportData) -> Result<String, String> {
    // 序列化数据
    let json_string = serde_json::to_string_pretty(&data.data)
        .map_err(|e| format!("序列化失败: {}", e))?;

    // 写入文件
    fs::write(&data.file_path, json_string)
        .map_err(|e| format!("写入文件失败: {}", e))?;

    Ok(data.file_path)
}

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
    tauri::Builder::default()
        .plugin(tauri_plugin_dialog::init()) // 必须添加这行初始化
        .plugin(tauri_plugin_fs::init())
        .plugin(tauri_plugin_updater::Builder::new().build())
        .plugin(tauri_plugin_store::Builder::new().build())
        .plugin(tauri_plugin_http::init())
        .plugin(tauri_plugin_opener::init())
        .invoke_handler(tauri::generate_handler![get_app_version,export_to_json])
        .setup(|app| {
            let window_labels = ["bp-backend", "bp-frontend", "bp-transition", "bp-score","bp-map"];
            
            for label in window_labels {
                if let Some(window) = app.get_webview_window(label) {
                    let app_handle = app.handle().clone();
                    let label = label.to_string();
                    
                    window.on_window_event({
                        let window = window.clone();
                        move |event| {
                            if let WindowEvent::CloseRequested { api, .. } = event {
                                api.prevent_close();
                                let _ = window.hide();
                                
                                // 使用 Emitter trait 的 emit 方法
                                let _ = app_handle.emit(
                                    "window-hidden", 
                                    serde_json::json!({
                                        "windowLabel": label,
                                        "timestamp": chrono::Local::now().to_rfc3339()
                                    })
                                );
                            }
                        }
                    });
                }
            }
            
            Ok(())
        })
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}
